package conson.tech.manage.app.controller.mobile;

import conson.tech.manage.api.app.constant.AppCommon;
import conson.tech.manage.api.app.dto.AppAdvertDTO;
import conson.tech.manage.api.app.form.AppAdvertForm;
import conson.tech.core.constant.SecurityConstants;
import conson.tech.core.response.Response;
import conson.tech.manage.app.entity.pojo.AppVersion;
import conson.tech.manage.app.service.AppAdvertService;
import conson.tech.manage.app.service.AppVersionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: AdvertisementMobileController
 * Description:
 * Author: HXL
 * Date: 2020/4/21 4:35 下午
 * Version: 1.0
 */
@Api(value = "app端使用的广告",tags = "app端使用的广告")
@RestController
@RequestMapping(SecurityConstants.MOBILEAPI)
public class AdvertMobileController {

    @Autowired
    private AppAdvertService appAdvertService;
    @Autowired
    private AppVersionService appVersionService;

    @ApiOperation(value = "根据广告位ID查询广告",notes = "根据广告位ID查询广告")
    @ApiImplicitParam(name = "form",value = "请求入参封装",required =true,dataType = "AppAdvertForm")
    @PostMapping("/queryAd")
    public Response<List<AppAdvertDTO>> queryAdList(@Valid @RequestBody AppAdvertForm form){
        Integer versionValue = getAdVersionValue(form);//获取版本值
        if (versionValue == null){
            return Response.success(new ArrayList<>());
        }
        List<AppAdvertDTO> dtoList =  appAdvertService.queryAdvertListByPlaceId(form.getPlaceId(),versionValue);
        return Response.success(dtoList);
    }
    private Integer getAdVersionValue(AppAdvertForm form) {
        List<AppVersion> versionList = appVersionService.queryAppVersionByVersionNum(form.getVersion(),form.getPlatformType());
        if (CollectionUtils.isEmpty(versionList)){
            return  null;
        }
        if (versionList.get(0).getVersionState() == AppCommon.VERSION_STATE_ONE){//是最新版本
            return AppCommon.VERSION_VALUE;
        }else {
            return versionList.get(0).getVersionValue();
        }
    }
}
